package com.oa.ht.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.mdp.core.service.BaseService;
import com.mdp.core.utils.BaseUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.oa.ht.entity.*;
import com.oa.ht.mapper.ContractDraftMapper;
import com.oa.ht.vo.ContractDraftAddVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@Service
public class ContractDraftService extends BaseService<ContractDraftMapper, ContractDraft> {
    static Logger logger = LoggerFactory.getLogger(ContractDraftService.class);

    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }
    @Lazy
    @Autowired
    private ContractCbService contractCbService;
    @Lazy
    @Autowired
    private ContractProductService contractProductService;
    @Lazy
    @Autowired
    private ContractConditionService contractConditionService;
    @Lazy
    @Autowired
    private ContractCardService contractCardService;
    @Lazy
    @Autowired
    private ContractProjectService contractProjectService;

    /**
     * 添加起草合同单
     *
     * @param contractDraftAddVo
     */
    @Transactional
    public void insertContractDraft(ContractDraftAddVo contractDraftAddVo) {
        User user = LoginUtils.getCurrentUserInfo();
        String branchId = user.getBranchId();

        //1.添加主表
        contractDraftAddVo.setReqDate(new Date());
        contractDraftAddVo.setBranchId(branchId);
        this.insert(contractDraftAddVo);

        //2.添加其他关联数据
        this.addOtherData(branchId, contractDraftAddVo);

        //3.填充word, 生成pdf

    }

    @Transactional
    public void addOtherData(String branchId, ContractDraftAddVo contractDraftAddVo) {
        String htId = contractDraftAddVo.getId();
        List<ContractCb> cbList = contractDraftAddVo.getCbList();
        List<ContractProduct> productList = contractDraftAddVo.getProductList();
        List<ContractCondition> conditionList = contractDraftAddVo.getConditionList();
        List<ContractProject> projectList = contractDraftAddVo.getProjectList();
        //2.添加成本预估
        if (!CollectionUtils.isEmpty(cbList)) {
            cbList.forEach(item -> {
                item.setCbId(contractCbService.createKey("cbId"));
                item.setBranchId(branchId);
                item.setHtId(htId);
            });
            contractCbService.batchInsert(cbList);
        }


        //3.添加产品
        if (!CollectionUtils.isEmpty(productList)) {
            productList.forEach(item -> {
                item.setId(contractProductService.createKey("id"));
                item.setBranchId(branchId);
                item.setHtId(htId);
            });
            contractProductService.batchInsert(productList);
        }


        //4.添加约定
        if (!CollectionUtils.isEmpty(conditionList)) {
            conditionList.forEach(item -> {
                item.setConditionId(contractConditionService.createKey("conditionId"));
                item.setBranchId(branchId);
                item.setHtId(htId);
            });
            contractConditionService.batchInsert(conditionList);
        }


        //4.添加项目
        if (!CollectionUtils.isEmpty(projectList)) {
            projectList.forEach(item -> {
                item.setId(contractProjectService.createKey("id"));
                item.setHtId(htId);
            });
            contractProjectService.batchInsert(projectList);
        }


    }


    /**
     * 查询合同起草的关联数据
     *
     * @param contractDraftList
     * @return
     */
    public void selectLinkData(List<Map<String, Object>> contractDraftList) {
        if (CollectionUtils.isEmpty(contractDraftList)) return;


        //合同id列表
        List<String> htIds = Lists.newArrayList();
        htIds = contractDraftList.stream().map(item -> (String) item.get("id")).collect(Collectors.toList());

        Map<String, Object> query = new HashMap<>();

        query.put("htIds", htIds);
        query.put("isThirdParty", "0");

        //1.关联成本
        List<ContractCb> cbList = contractCbService.selectCbByIds(query);
        //2.关联产品
        List<ContractProduct> productList = contractProductService.selectProByIds(query);
        //3.关联机会
        List<ContractCondition> conditionList = contractConditionService.selectConditionByIds(query);

        //3.关联项目
        List<ContractProject> projectList = contractProjectService.selectProjectByIds(query);

        //组装数据
        Multimap<String, ContractCb> cbMultimap = ArrayListMultimap.create();
        cbList.stream().forEach(item -> cbMultimap.put(item.getHtId(), item));

        Multimap<String, ContractProduct> productMultimap = ArrayListMultimap.create();
        productList.stream().forEach(item -> productMultimap.put(item.getHtId(), item));

        Multimap<String, ContractCondition> conditionMultimap = ArrayListMultimap.create();
        conditionList.stream().forEach(item -> conditionMultimap.put(item.getHtId(), item));

        contractDraftList.stream().forEach(item -> {
            List<ContractCb> cbList1 = (List<ContractCb>) cbMultimap.get((String) item.get("id"));
            item.put("cbList", cbList1);

            List<ContractProduct> productList1 = (List<ContractProduct>) productMultimap.get((String) item.get("id"));
            item.put("productList", productList1);

            List<ContractCondition> conditionList1 = (List<ContractCondition>) conditionMultimap.get((String) item.get("id"));
            item.put("conditionList", conditionList1);
        });
    }

    /**
     * 修改客户合同起草
     *
     * @param contractDraftAddVo
     */
    @Transactional
    public void updateContractDraft(ContractDraftAddVo contractDraftAddVo) {
        User user = LoginUtils.getCurrentUserInfo();

        //1.修改主表
        this.updateByPk(contractDraftAddVo);

        //2.删除关联数据，重新添加
        Map<String, Object> condition = new HashMap<>();
        condition.put("htId", contractDraftAddVo.getId());

        this.contractCbService.deleteByWhere(BaseUtils.fromMap(condition, ContractCb.class));
        this.contractProductService.deleteByWhere(BaseUtils.fromMap(condition, ContractProduct.class));
        this.contractConditionService.deleteByWhere(BaseUtils.fromMap(condition, ContractCondition.class));
        this.contractProjectService.deleteByWhere(BaseUtils.fromMap(condition, ContractProject.class));

        //重新添加数据
        this.addOtherData(user.getBranchId(), contractDraftAddVo);
        //生成资产卡片,该步骤应放在流程结束
        //TODO:
        if ("1".equals(contractDraftAddVo.getStatus())) {
            contractCardService.generateContractCard(contractDraftAddVo.getId());
        }
    }


    /** 请在此类添加自定义函数 */
}

